<template>
  <div class="user-dialog bigDialog">
    <el-dialog
        ref="ruleFormRef"
        :model-value="dialogData.props.dialogFormVisible"
        :title="dialogData.props.title"
        :before-close="close"
        :width="dialogData.formLabelWidth"
        :close-on-click-modal="false"
        draggable
    >
      <div>
        <!-- 基础信息 -->
        <div>
          <el-form
              :model="dialogData.formData"
              :inline="true"
              label-width="160px"
              :rules="dialogData.rules"
              ref="addform"
              require-asterisk-position="left"
              size="default"
              scroll-to-error="true"
          >
            <div class="basicstyle">
              <div class="itemStyle ">
                <!-- <p class="titleName">证书信息</p> -->

                <el-form-item label="公告标题：" prop="title" required>
                  <el-input
                      placeholder="请输入公告标题"
                      v-model="dialogData.formData.title"
                      maxlength="50"

                  />
                </el-form-item>
                <el-form-item label="公告内容：" prop="context" required>
                  
                  <el-input
                      type="textarea"
                      show-word-limit
                      maxlength="500"
                      rows="4"
                      placeholder="请输入公告内容"
                      v-model="dialogData.formData.context"
                  />
                </el-form-item>
                <el-form-item label="发布单位：" prop="publisherName" required>
                  <el-input
                      placeholder="请输入发布单位"
                      maxlength="50"
                      v-model="dialogData.formData.publisherName"
                  />
                </el-form-item>
                <el-form-item label="发布时间：" prop="publisherTime" required>
                  <el-date-picker
                    v-model="dialogData.formData.publisherTime"
                    type="datetime"
                    placeholder="请选择发布时间"
                    :disabled-date="disabledDate"
                  />
                </el-form-item>
                <el-form-item label="上传附件：" >
                      <el-upload
                              v-model:file-list="dialogData.formData.filedata"
                              class="upload-demo"
                              action="api/common/uploadFile"
                              
                              drag
                              :on-preview="handlePreview"
                              :on-remove="handleRemove"
                              :before-remove="beforeRemove"
                              :on-exceed="handleExceed"
                              :before-upload="filebeforeUpload"
                              :on-success="uploadSuccess"
                              :on-change = 'filehandleChange'
                              accept=".pdf,.docx,.xls,.xlsx,.ppt,.mp4,.pptx"
                          >
                              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                              <div class="el-upload__text">
                                  将文件拖至此处, 或<em>点击上传</em>
                              </div>
                              <template #tip>
                              <div class="el-upload__tip">
                                  可上传PDF/Word/Excel/PPT文件，大小不超过100MB；MP4视频，大小不超过500MB
                              </div>
                              </template>
                          </el-upload>
                  </el-form-item>
                  <div class="ml-32">
                      <el-table
                        :data="dialogData.formData.equipmentFiles"
                        :header-cell-style="{ background: 'rgba(242,245,250,1)'}"     
                        border
                        style="width: 100%"
                    > 
                        <el-table-column prop="name"   label="文件名" min-width="10%" >
                          <template #default="scope">
                            <span @click="handleLook( scope.row)" class="name-color">{{scope.row.name}}</span> 
                          </template>
                        </el-table-column>
                        <el-table-column prop="time"   label="上传时间" min-width="10%" />
                        <!-- <el-table-column prop="fileSize"   label="文档大小" min-width="10%" /> -->
                        <el-table-column prop="fileTypeStr"   label="文档格式" min-width="10%" />
                        <el-table-column label="操作列" width="100" min-width="10%">
                            <template #default="scope">
                                <!-- <span class="buttonFun cursor" @click="handleLook( scope.row)">预览</span>
                                <span class="buttonFun cursor" @click="download(scope.row)">下载</span> -->
                                <el-popconfirm 
                                        width="520"
                                        confirm-button-text="确定"
                                        cancel-button-text="取消"
                                        @confirm="handleDelete(scope.$index, scope.row)"
                                        title="你确定要删除这条数据吗?">
                                        <template #reference>
                                        <span class="buttonFun cursor">删除</span>
                                        </template>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                  </div>
                    
              </div>
            </div>
          </el-form>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button
              class="btn-mixins-clear-default"
              @click="close"
          >取消</el-button>
          <el-button
              class="btn-mixins dia-suc"
              @click="success(addform)"
          >保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <previewBox :previewDialog="dialogData.previewDialog"
    :file="dialogData.formData.file" @closePreview="closePreview()">
  </previewBox>
</template>
<script  setup>
import previewBox from '../../preview/preview.vue'
import { defineProps, ref,onBeforeMount } from "vue";
import { reactive, watch, defineEmits } from "vue";
import { getymdhms,disabledDate } from '@/utils/auth'
import { ElNotification ,ElMessage, ElMessageBox } from "element-plus";
import {
  sysnoticesubmit as sysnoticesubmit
} from '@/api//user.js'
import { inject,getCurrentInstance  } from 'vue'
import store from "@/store";
const instance = getCurrentInstance();
const emits = defineEmits(["update:modelValue"]);
const addform = ref('');
const dialogData = reactive({
  formLabelWidth:instance.proxy.formLabelWidth,
  rules:{
    title:[{ required: true,pattern: '[^ \x20]+', message: "请输入公告标题", trigger: "blur" }],
    context:[{ required: true,pattern: '[^ \x20]+', message: "请输入公告内容", trigger: "blur" }],
    publisherName:[{ required: true,pattern: '[^ \x20]+', message: "请输入发布单位", trigger: "blur" }],
    publisherTime:[{ required: true, message: "请选择发布时间", trigger: "Chaneg" }]
  },
  props:{
    title:'',
    dialogFormVisible:'',
  },
  formData:{
    filedata:[],
    equipmentFiles:[],
    file: {}
  },
  previewDialog: false,
  dropdown:{
    levelList:[
      {
        label:'一级保养',
        value:"1"
      },{
        label:'二级保养',
        value:"2"
      },{
        label:'三级保养',
        value:"3"
      },{
        label:'四级保养',
        value:"4"
      },{
        label:'五级保养',
        value:"5"
      },{
        label:'日常保养',
        value:"6"
      },{
        label:'常规润滑',
        value:"7"
      }
    ],
  },
})
let props = defineProps({
  dialogFormVisible: {
    type: Boolean,
  },
  dialogTitle: {
    type: String,
  },
  dialogTableValue: {
    type: Object,
    default: () => {},
  },

});


onBeforeMount(()=>{
//   getEightWorkTypeFun()
//   getUserListFun()
//   getMaintenanceProjectCodeFun()
  // let user = JSON.parse(localStorage.getItem('userData'))
  // // alert(user.userId)
  // dialogData.formData.createUser=user.userId;
  // dialogData.formData.createUserName=user.realName;
  // dialogData.formData.updateUser=user.userId;
  // dialogData.formData.updateUserName=user.realName;
  // dialogData.formData.stauts="1";
})
watch(
    () => props.dialogFormVisible,
    () => {
      dialogData.props.title = props.dialogTitle;
      dialogData.props.dialogFormVisible = props.dialogFormVisible;
      // dialogData.dropdown.materialTypeList = props.materialTypeList;
      // console.log(dialogData.dropdown.materialTypeList)
      if (dialogData.props.title === "编辑" ){
        dialogData.formData = props.dialogTableValue;
        // dialogData.formData.equipmentFiles = []
      }else {
        dialogData.formData= {};
        dialogData.formData.equipmentFiles = []
      }

    },
    { deep: true, immediate: true }
);
const filebeforeUpload = (file) =>{
    // ".pdf,.docx,.doc,.xls,.xlsx,.ppt,.mp4,.pptx"
        const typeExtensions= ['pdf', 'docx','xlsx','mp4','pptx']; // 可以自定义需要支持的音频格式
        const fileExtension = file.name.split('.').pop().toLowerCase(); // 根据文件名获取文件扩展名并转换为小写字母形式
        if (typeExtensions.includes(fileExtension) == false) {
            ElMessage({
                type: 'error',
                message: '只能上传PDF，Word，Excel，PPT和MP4格式的文件',
            })
        }
        return typeExtensions.includes(fileExtension);
      }
/**
 * 附件上传大小校验
 */
const filehandleChange = (file, fileList) => {
  console.log("22222")
  //1、判断文件大小是否合法，文件限制不能大于100M
  const isLt5M = file.size / 1024 / 1024 < 100;
	if (!isLt5M) {
    ElMessage({
        type: 'error',
        message: '上传文件大小不能超过 100MB!',
    })
    fileList.splice(-1,1) //移除当前超出大小的文件
		return false;
  }
    // 2、限制重复上传
  // 将fileList去重后的长度如果小于目前数组的长度，说明有重复
    const newListLength = new Set(fileList.map(item=>item.name)).size;
	const listLength = fileList.length;
	if(listLength > newListLength) {
    ElMessage({
        type: 'error',
        message: '上传文件重复!',
    })
    fileList.splice(-1, 1) //移除当前重复的文件即末尾对象
		return false;
	}
}
// 提交附件
const uploadSuccess = (uploadFile)=>{
    // if (!fileform) return;
    // fileform.validate(async (valid) => {
        // if (valid) {
            console.log(uploadFile)
            let fileData = JSON.parse(JSON.stringify(dialogData.formData.filedata ))
            if(fileData&&fileData.length&&fileData.length>0){
                fileData.forEach((file,index)=>{
                    let obj = {
                        name:file.name.substring(0,file.name.lastIndexOf('.')),
                        time:getymdhms(new Date()),
                        fileSize:file.size / 1024 / 1024+'MB',
                        fileTypeStr:file.name.substring(file.name.lastIndexOf('.'),file.name.length),
                        url:file.response.body
                    }
                    dialogData.formData.equipmentFiles.push(obj)
                })
            }
            console.log(dialogData.formData.equipmentFiles)
            dialogData.formData.filedata = []
        // }
    // })
}
//预览
const handleLook = (row) => {
  dialogData.previewDialog = true
  dialogData.formData.file = row
}
const closePreview =() => {
  dialogData.previewDialog = false
}


//删除
const handleDelete = (index,row)=>{
    dialogData.formData.equipmentFiles.splice(index, 1)
}
const close = () => {
  addform.value.resetFields();
  emits("update:modelValue", false);
};

const success = (addform) => {
  if (!addform) return;
  addform.validate(async (valid) => {
    if (valid) {
      let obj = JSON.parse(JSON.stringify(dialogData.formData));
      obj.publisherTime  =  obj.publisherTime? getymdhms( obj.publisherTime):'';
      let user = JSON.parse(localStorage.getItem('userData'))
      obj.createUser = user.userId;
      obj.createUserName = user.realName;
      sysnoticesubmit(obj).then((res)=>{
        if(res.code ===200){
          close()
        }else{
          ElNotification({
            title: '警告',
            message: res.message?res.message:'服务器异常',
            type: 'warning',
          })
          if(res.message.indexOf('token已过期')>-1  ){
            store.dispatch('app/logout')
          }
        }
      })
    } else {
      return false;
    }
  });
};
</script>

<style lang = 'less' scoped>
.user-dialog {
  .name-color{
    color: #2E83FC;
  }
  .basictitle {
    font-size: 18px;
    margin: 16px 0 24px;
    color: #333333;
  }
}
:deep(.el-form-item__label ){
  font-size: 14px;
}

.itemStyle{
  .titleName{
    color: #4B515B;
    font-size: 14px;
    padding-left: 8px;
    margin-left: 8px;
    border-left: 5px solid #2E83FC;
    margin-bottom: 16px;
  }
}
.bigDialog{
  :deep(.el-input){
    width: 100%;
  }
  :deep(.el-select){
    width:100%;
  }
  :deep(.el-form-item__content) {
    width: 100%;
  }
  :deep(.el-dialog__footer) {
    padding-top: 16px;
    background-color: #ffffff;
  }
  :deep(.el-dialog__body) {
    padding: 0;
    max-height: 550px;
    overflow-y: auto;
    overflow-x: hidden;
    background-color: #ffffff;
    padding: 32px 88px 16px 32px;
  }
  :deep(.el-dialog__header) {
    border-bottom: 1px solid #cccccc;
    padding: 16px;
    margin-right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  :deep(.el-dialog__title) {
    color: #1C222C;
    font-size: 20px;
    width: 100px;
  }
  :deep(.el-dialog__headerbtn ){
    position: static;
    top: 0px;
    right: 0;
    padding: 0;
    width: auto;
    height: auto;
  }

  :deep(.el-form-item__label ){
    font-size: 14px;
  }
  :deep(.el-form) {
    position: relative;
  }

  :deep(.el-form-item__content) {
    width: 100%;
  }
  :deep(.el-form--inline .el-form-item){
    width:100%
  }
}
</style>
